<?php

namespace app\admin\controller\sales;

//use app\admin\controller\customer\Customer;
use app\common\controller\Backend;
use app\common\model\goods\Goods;
use app\common\model\goods\GoodsHouseStock;
use app\common\model\sales\RetreatGoods;
use app\common\model\customer\Customer;
use app\common\model\Storehouse;
use think\Db;
use think\Exception;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Retreat extends Backend
{
    
    /**
     * Retreat模型对象
     * @var \app\common\model\change\Retreat
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\sales\Retreat;

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            $this->handlefilter();
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['salescheckout','salesslip','customer','storehouse'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['salescheckout','salesslip','customer','storehouse'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->visible(['id','createtime','number','collectiontime','explain','abstract','operator','company','status','tax']);
                $row->visible(['salescheckout']);
				$row->getRelation('salescheckout')->visible(['number']);
				$row->visible(['salesslip']);
				$row->getRelation('salesslip')->visible(['number']);
				$row->visible(['customer']);
				$row->getRelation('customer')->visible(['company']);
				$row->visible(['storehouse']);
				$row->getRelation('storehouse')->visible(['name']);
            }
            $list = collection($list)->toArray();
            $statuss = $this->model->retreat_status();
            foreach ($list as $k=> $v){
                $list[$k]['ystatus'] = $v['status'];
                $list[$k]['status'] = $statuss[$v['status']];
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    public function detail($ids=null){
        $group = Db::name('auth_group_access')->alias('a')->where(array('uid' => session('admin')['id']))->join('zax_auth_group g', 'a.group_id = g.id')->find();

        $row = $this->model->find($ids);
        if(!$row){
            $this->error('退货单不存在');
        }
        if ($this->request->isAjax()) {
            $status = input('status/d',0);

            if(empty($status)){
                $this->error('状态异常');
            }
            if($row['status'] !=1){
                $this->error('状态异常');
            }
            Db::startTrans();
            try {
                $odata['status'] = $status;

                //驳回
                if($status == 4){
                    $RetreatGoods = new RetreatGoods;
                    $RetreatGoods->save(array('status'=>0),array('sales_retreat_id'=>$ids));
                    $type = 2;
                }
                $res = $this->model->save($odata,array('id'=>$ids));
                if($status == 2){
                    $group = Db::name('auth_group_access')->alias('a')->where(array('uid'=>session('admin')['id']))->join('zax_auth_group g','a.group_id = g.id')->find();
                    $custrow = Customer::find($row['customer_id']);
                    Db::name('analysis')->insert(array(
                        'is_income'=>1,
                        'source'=>9,
                        'cost'=>-$row['actual_cost'],
                        'admin_id'=>$row['admin_id'],
                        'group_id'=>$row['group_id'],
                        'company'=>$row['company'],
                        'source_id' => $row['id'],
                        'obj_id' => $row['customer_id'],
                        'operator'=>$row['operator'],
                        'controller'=>'sales/retreat',
                        'settle_name'=>$custrow['company'],
                        'number'=>$row['number'],
                        'createtime'=>time(),
                        'storehouse_id' => $row['storehouse_id'],
                        'explain'=>$row['explain'],//摘要
                    ));
                    $type =1;
                }
                if(!$res){
                    Db::rollback();
                    throw new Exception('数据异常');
                }
                Db::name('examine_log')->insert(array(
                    'admin_id'=>session('admin')['id'],
                    'type'=>$type,
                    'createtime'=>time(),
                    'controller'=>'sales/retreat',
                    'source_id'=>$ids,
                    'source'=>9,
                    'remark'=>'销售退货单',
                    'number'=>isset($row['number'])?$row['number']:'',
                ));

                Db::commit();
                return  array(
                    'code'=>1,
                    'msg'=>'审核成功',
                );
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
        $list = Db::name('sales_retreat_goods')
            ->field('g.id,goods_num,sale_price,ht_price,tax,remark,title,place_origin,number,unit,specs,storehouse_id,costPrice,sfhj')
            ->alias('sg')
            ->where(array('sales_retreat_id'=>$ids))
            ->join('goods g','sg.goods_id = g.id')
            ->select();

        foreach ($list as $k => $v){
            $GoodsHouseStock = new GoodsHouseStock;
            $list[$k]['xstock'] = $GoodsHouseStock->getfictstock($v['id'],$v['storehouse_id']);
            $list[$k]['stock'] = $GoodsHouseStock->getstock($v['id'],$v['storehouse_id']);
        }
        $this->assign('admin',session('admin'));
        $this->assign('gname',$group['name']);
        $this->assign('list',$list);
        $this->assign('row',$row);
        $this->assign('is_finance',input('is_finance/d',0));
//        $arr = explode('/',$_SERVER['REQUEST_URI']);
//        $this->assign('turl', handlePrefix().'://'.$_SERVER['SERVER_NAME'].'/'.$arr[1]);
        return $this->view->fetch();
    }

    public function enter($ids = null){
        $status = input('status/d',0);
        if(empty($status)){
            $this->error('状态异常');
        }
        $row = $this->model->find($ids);
        if(!$row){
            $this->error('退货单不存在');
        }
        if($row['status'] !=2){
            $this->error('状态异常');
        }
        Db::startTrans();
        try {
            $odata['status'] = $status;
            if($status == 3) {
                //增加库存
                $rgoods = new RetreatGoods();
                $list = $rgoods->where(array('sales_retreat_id' => $ids))->select();
                $group = Db::name('auth_group_access')->alias('a')->where(array('uid'=>session('admin')['id']))->join('zax_auth_group g','a.group_id = g.id')->find();
                foreach ($list as $v) {
                    $GoodsHouseStock = new GoodsHouseStock;
                    //增加库存
                    //减增加存 根据当时的价格来增加库存价值
                    $GoodsHouseStock = new GoodsHouseStock();
                    $rr = $GoodsHouseStock->addstock($v['goods_id'],$row['storehouse_id'],$v['goods_num'],$v['costPrice'],1);
                    if(!$rr){
                        throw new Exception('库存计算错误');
                    }
//                    $goods = new \app\common\model\goods\Goods();
//                    $final_cost = $goods->getcost($v['goods_id'],$row['storehouse_id']);
//
//                    $GoodsHouseStock = new GoodsHouseStock;
//                    $stock = $GoodsHouseStock->getstock($v['goods_id'],$row['storehouse_id']);

                    $hgood = Db::name('goods_house_stock')->where(array('goods_id'=>$v['goods_id'],'storehouse_id'=>$row['storehouse_id']))->find();



                    Db::name('goods_stock_log')->insert(array(
                        'goods_id'=>$v['goods_id'],
                        'createtime'=>time(),
                        'number'=>$row['number'],
                        'type'=>'销售退货单',
                        'source'=>9,
                        'type_id'=>$row['id'],
                        'enter_num'=>$v['goods_num'],
//                            'out_num'=>$v['goods_num'],
                        'before_num'=>$hgood['stock']-$v['goods_num'],
                        'now_num'=>$hgood['stock'],
                        'storehouse_id'=>$row['storehouse_id'],
//                       'remark'=>$v['goods_id'],
                        'controller'=>'sales/retreat',
                        'admin_id'=>session('admin')['id'],
                        'group_id'=>$group['group_id'],
                        'company'=>$group['name'],
                        'operator'=>session('admin')['nickname'],
//                        'final_cost'=>$final_cost,
                        'final_cost'=>$v['costPrice'], //记录的金额应该是入库的加权单价
                        'bill_cost'=>bcmul($v['costPrice'],$v['goods_num'],4), //记录的金额应该是入库的采购成本
                        'balance'=>$hgood['balance'], //记录的金额当前库存总额
                    ));



                }
            }
            $res = $this->model->save($odata,array('id'=>$ids));
            if(!$res){
                Db::rollback();
                throw new Exception('数据异常');
            }
            Db::commit();
            return  array(
                'code'=>1,
                'msg'=>'审核成功',
            );
        }catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }
    }
    public function cancelbill($ids = null){
        if (!$this->request->isAjax()) {
            $this->error('非法操作');
        }
        $reason = input('reason');
        if(empty($reason)){
            $this->error('理由必须填写');
        }
        $row = $this->model->find($ids);
        if($row['status'] == 1 || $row['status'] >3){
            $this->error('状态异常');
        }
        $analysis = Db::name('analysis')->where(array(
            'source'=>9,
            'source_id' => $row['id'],
            'storehouse_id' => $row['storehouse_id'],
        ))->find();
        //只有财务数据在待处理的时候 才能处理
        if($analysis['status'] != 1){
            $this->error('财务状态异常,请处理');
        }
        /*
        * 取消财务订单
        * 如果已经入库  回退数据
        *
        */
        $group = Db::name('auth_group_access')->alias('a')->where(array('uid'=>session('admin')['id']))->join('zax_auth_group g','a.group_id = g.id')->find();
        Db::startTrans();
        try {
            $this->model->save(array('status'=>5),array('id'=>$ids));

            $RetreatGoods = new RetreatGoods;
            $RetreatGoods->save(array('status'=>0),array('sales_retreat_id'=>$ids));

            if($row['status'] == 3){ //已收货 要把库存减少
                $rgoods = new RetreatGoods();
                $list = $rgoods->where(array('sales_retreat_id' => $ids))->select();



                foreach ($list as $v){
                    $hgood = Db::name('goods_house_stock')->where(array('goods_id'=>$v['goods_id'],'storehouse_id'=>$row['storehouse_id']))->find();
                    if($hgood['stock'] == 0){
                        throw new Exception('库存为0');
                    }


                    if($hgood['stock'] == $v['goods_num']){
                        $balance = 0;
                    }else{
                        $balance = $hgood['balance']-bcmul($v['costPrice'],$v['goods_num'],4);
                    }

                    Db::name('goods_stock_log')->insert(array(
                        'goods_id'=>$v['goods_id'],
                        'createtime'=>time(),
                        'number'=>$row['number'],
                        'type'=>'销售退货单',
                        'source'=>9,
                        'type_id'=>$row['id'],
//                        'enter_num'=>$v['goods_num'],
                        'out_num'=>$v['goods_num'],
                        'before_num'=>$hgood['stock'],
                        'now_num'=>$hgood['stock']-$v['goods_num'],
                        'storehouse_id'=>$row['storehouse_id'],
//                       'remark'=>$v['goods_id'],
                        'controller'=>'sales/retreat',
                        'admin_id'=>session('admin')['id'],
                        'group_id'=>$group['group_id'],
                        'company'=>$group['name'],
                        'operator'=>session('admin')['nickname'],
//                        'final_cost'=>$final_cost,
                        'final_cost'=>$v['costPrice'], //记录的金额应该是入库的加权单价
                        'bill_cost'=>bcmul($v['costPrice'],$v['goods_num'],4), //记录的金额应该是入库的采购成本
                        'balance'=>$balance, //记录的金额当前库存总额
                        'is_cancel'=>1,
                    ));
                    $GoodsHouseStock = new GoodsHouseStock();
                    $rr = $GoodsHouseStock->reducestock($v['goods_id'],$row['storehouse_id'],$v['goods_num'],$v['costPrice']);
                    if(!$rr){
                        throw new Exception('库存计算错误');
                    }
                }


            }

            Db::name('cancel_bill')
                ->insert(array(
                    'reason' => $reason,
                    'source' => 9,
                    'admin_id' => session('admin')['id'],
                    'group_id' => $group['group_id'],
                    'company' => $group['name'],
                    'operator' => session('admin')['nickname'],
                    'controller' => 'sales/retreat',
                    'source_id' => $row['id'],
                    'number' => isset($row['number'])?$row['number']:'',
                    'createtime' => time(),
                ));
            //审核记录
            Db::name('examine_log')->insert(array(
                'admin_id'=>session('admin')['id'],
                'type'=>3,
                'createtime'=>time(),
                'controller'=>'sales/retreat',
                'source_id'=>$ids,
                'source'=>9,
                'remark'=>'销售退货单',
                'number'=>isset($row['number'])?$row['number']:'',
            ));

            //财务单据作废
            $ress = Db::name('analysis')->where(array(
                'id' => $analysis['id']
            ))->update(array('status' => 4));
            if (!$ress) {
                throw new Exception('数据异常');
            }

            Db::commit();
            return array(
                'code' => 1,
                'msg' => '成功'
            );
        }catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }
    }
    public function add(){
        if ($this->request->isAjax()){
            $params = input();
            $storehouse_id = input('storehouse_id');
            $customer_id = input('customer_id');
            $tax = input('tax');
            $explain = input('explain');
            $allfare = input('allfare');
            $discount = input('discount');
            $discount_explain = input('discount_explain');
            $actual_cost = input('actual_cost');
            $declare = input('declare');
            $retreat_num = 0;
            if(empty($storehouse_id) || empty($customer_id)){
                $this->error('缺必要参数');
            }
            $gdata = $params['row'];
            foreach ($gdata as $v){
                if(empty($v['goods_num'])){
                    $this->error('数量不能为空');
                }
                $retreat_num +=$v['goods_num'];
            }
            Db::startTrans();
            try {
                $group = Db::name('auth_group_access')->alias('a')->where(array('uid' => session('admin')['id']))->join('zax_auth_group g', 'a.group_id = g.id')->find();
                $num = Db::name('sales_retreat')->where(array('createtime'=>array('>',strtotime(date('Y-m-d',time())))))->count();
                $retreatdata = array(
                    'number'=>'XT-T-'.date('Y-m-d').'-'.getnumber($num),
                    'collectiontime'=>time(),
                    'customer_id'=>$customer_id,
                    'storehouse_id'=>$storehouse_id,
                    'explain'=>$explain,
//                'abstract'=>$abstract,
                    'tax'=>$tax,
                    'admin_id'=>session('admin')['id'],
                    'group_id'=>$group['group_id'],
                    'company'=>$group['name'],
                    'sales_slip_id' => 0,
                    'operator'=>session('admin')['nickname'],
                    'sales_checkout_id' => 0,
                    'allfare' => $allfare,
                    'discount' => $discount,
                    'discount_explain' => $discount_explain,
                    'actual_cost' => $actual_cost,
                    'declare' => $declare,
                    'retreat_num' => $retreat_num,
                );
                $res = $this->model->save($retreatdata);
                if(empty($res)){
                    throw new Exception('添加失败');
                }
                Db::name('bill')->insert(array(
                    'storehouse_id'=>$storehouse_id,
                    'bill_id'=>$this->model->id,
                    'type'=>9,
                    'admin_id'=>session('admin')['id'],
                    'group_id'=>$group['group_id'],
                    'createtime'=>time(),
                ));
                $sdata = [];

                foreach ($gdata as $k => $v) {
                    $gods = new \app\common\model\goods\Goods();
                    $costPrice = $gods->getcost($v['goods_id'],$storehouse_id);
                    if(empty($costPrice)){
                        throw new Exception($v['goods_id'].'商品无法退货');
                    }
                    $sdata[] = array(
                        'goods_id' => $v['goods_id'],
                        'goods_num' => $v['goods_num'],
                        'sale_price' => $v['sale_price'],
                        'ht_price' => $v['ht_price'],
                        'tax' => $v['tax'],
                        'sfhj' => $v['sfhj'],
                        'remark' => $v['remark'],
                        'sales_checkout_id' => 0,
                        'sales_slip_id' => 0,
                        'sales_retreat_id' => $this->model->id,
                        'storehouse_id'=>$storehouse_id,
                        'customer_id' => $customer_id,
                        'costPrice' => $costPrice,
                        'admin_id'=>session('admin')['id'],
                        'group_id'=>$group['group_id'],
                        'company'=>$group['name'],
                        'operator'=>session('admin')['nickname'],
                    );
                }
                $RetreatGoods = new RetreatGoods();
                $RetreatGoods->saveAll($sdata);
                Db::commit();
                return array(
                    'code'=>1,
                    'msg'=>'添加成功',
                );

            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
        return $this->view->fetch();
    }

    public function seach(){
        $house_id = input('house_id/d',0);
        $customer_id = input('customer_id/d',0);
        if ($this->request->isAjax()){
            $filter = json_decode(input('filter'),true);
            $where = [];
            foreach ($filter as $k=> $v){
                if($k == 'storehouse_id'){
                    $where['storehouse_id']= $v;
                }
                if($k == 'customer_id'){
                    $where['customer_id']= $v;
                }
            }
            $page = input('offset/d',0);
            $pagesize = input('limit/d',0);
            $total = Db::name('sales_checkout_goods')
                ->where($where)
                ->group('goods_id')
                ->alias('cg')
                ->join('goods g','cg.goods_id = g.id')
                ->field('g.title,g.specs')
                ->count();
            $list = Db::name('sales_checkout_goods')
                ->where($where)
                ->group('goods_id')
                ->alias('cg')
                ->join('goods g','cg.goods_id = g.id')
                ->limit($page,$pagesize)
                ->field('g.id,g.title,g.specs')
                ->select();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        $this->assign('customer_id',$customer_id);
        $this->assign('house_id',$house_id);
        return $this->view->fetch();
    }
}
